package com.ljx.itbbs.server.mall.service.lock;

import cn.hutool.core.lang.UUID;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @Author: LiJunXi
 * @Description: 自定义Redis锁
 * @Date: 2024-03-30  22:16
 */
public class CustomRedisLock implements ILock{

    // 随机UUID前缀
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "_";

    private StringRedisTemplate stringRedisTemplate;

    private String key;

    public CustomRedisLock(String key, StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.key = key;
    }

    @Override
    public Boolean tryLock(Long time, TimeUnit timeUnit) {
        // 线程ID，这里加上了随机的UUID前缀，防止集群下误删
        String id = ID_PREFIX + Thread.currentThread().getId();
        String finalKey = ID_PREFIX + key;
        return stringRedisTemplate.opsForValue().setIfAbsent(finalKey, id, time, timeUnit);
    }

    @Override
    public void unLock() {
        String finalKey = ID_PREFIX + key;
        stringRedisTemplate.delete(finalKey);
    }
}
